<template>
  <div class="import">
    <UploadExcel :on-success="success" :before-upload="false" />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { exportEmployeeAPI } from '@/api/employees'
import { IExcel } from '@/model/interface/excel'

@Component({ name: 'Import' })
export default class extends Vue {
  async success(data: IExcel) {
    console.log(data)
    try {
      const newData = this.formatExcel(data)
      // console.log(newData)
      await exportEmployeeAPI(newData)
      this.$message.success('操作成功')
      this.$router.back()
    } catch (e) {
      this.$message.success(e)
      console.log(e)
    }
  }

  // 格式化excel
  formatExcel(data: IExcel) {
    // 表头转换
    // newData.header = data.header.map(key_zh => this.zh2en(key_zh))
    // 数据转换
    return data.results.map(item => {
      const newItem: any = {}
      // 字段
      Object.keys(item).map(keyZh => {
        // 取出转换后的英文字符串
        const keyEn: any = this.$t(`dictionary.${keyZh}`)
        // 包含 '日期' 字段的值需要格式化
        if (keyZh.indexOf('日期') !== -1) {
          return (newItem[keyEn] = new Date(this.formatDate(item[keyZh], '/')))
        }
        // 其他可直接输出
        return (newItem[keyEn] = item[keyZh])
      })
      return newItem
    })
  }

  // 格式化成js日期
  formatDate(numb: number, format: string) {
    const time = new Date((numb - 1) * 24 * 3600000 + 1)
    time.setFullYear(time.getFullYear() - 70)
    const year = time.getFullYear() + ''
    const month = time.getMonth() + 1 + ''
    const date = time.getDate() - 1 + ''
    if (format && format.length === 1) {
      return year + format + month + format + date
    }
    return (
      year +
      (Number(month) < 10 ? '0' + month : month) +
      (Number(date) < 10 ? '0' + date : date)
    )
  }
}
</script>

<style scoped>
.import {
  margin-top: 100px;
}
</style>
